package com.example.delicioushunter.view.activity;

import java.util.ArrayList;

import com.example.delicioushunter.R;
import com.example.delicioushunter.control.databasecontrol.BookControl;
import com.example.delicioushunter.model.database.DHDatabaseHelper;
import com.example.delicioushunter.model.object.Book;
import com.example.delicioushunter.view.adapter.BookAdapter;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class BookActivity extends Activity {

	protected static final int REQUEST_CODE_BOOK_ID = 1;
	/**
	 * Views
	 */
	private EditText editBookTitle;
	private ImageView imgAdd, imgCancel, imgSave;
	private GridView gridBook;

	/**
	 * Properties
	 */
	private ArrayList<Book> books;
	private BookAdapter adapter;
	private SQLiteDatabase wdb;
	private SQLiteDatabase rdb;
	private DHDatabaseHelper helper;
	private Context mContext;
	private int selected = 0;
	private int index = 0;
	private ProgressDialog pd;
	private int book_full_empty, book_row_empty;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_book);
		
		book_full_empty = getResources().getInteger(R.integer.book_full_empty);
		book_row_empty = getResources().getInteger(R.integer.book_row_empty);
		Log.d("Size", book_full_empty + " "+ book_row_empty);
		
		
		gridBook = (GridView) findViewById(R.id.gridBook);
		books = new ArrayList<Book>();
		adapter = new BookAdapter(mContext, books);
		gridBook.setAdapter(adapter);
		gridBook.setOnItemClickListener(mOnItemClick);
		
		helper = new DHDatabaseHelper(mContext);
		loadBook();
		loadView();
	}
	
	private void loadView(){
		editBookTitle = (EditText) findViewById(R.id.editBookTitle);
		imgCancel = (ImageView) findViewById(R.id.imgCancel);
		imgSave = (ImageView) findViewById(R.id.imgSave);
		imgAdd = (ImageView) findViewById(R.id.imgAdd);
		
		editBookTitle.setVisibility(View.GONE);
		imgCancel.setVisibility(View.GONE);
		imgSave.setVisibility(View.GONE);

		imgAdd.setOnTouchListener(imgAddTouch);
		imgCancel.setOnTouchListener(imgCancelTouch);
		imgSave.setOnTouchListener(imgSaveTouch);
	}

	private OnTouchListener imgAddTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			editBookTitle.setVisibility(View.VISIBLE);
			imgCancel.setVisibility(View.VISIBLE);
			imgSave.setVisibility(View.VISIBLE);
			return false;
		}
	};

	private OnTouchListener imgCancelTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			editBookTitle.setText(null);
			editBookTitle.setVisibility(View.GONE);
			imgCancel.setVisibility(View.GONE);
			imgSave.setVisibility(View.GONE);
			return false;
		}
	};

	private OnTouchListener imgSaveTouch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
					R.drawable.book_cover);

			wdb = helper.getWritableDatabase();
			Book book = new Book();
			book.setBook_title(editBookTitle.getText().toString());
			book.setImage(bitmap);

			BookControl control = new BookControl();
			int lastId = control.addBook(book, wdb);
			bitmap.recycle();
			bitmap = null;
			Toast.makeText(mContext, "Successfully " + lastId, Toast.LENGTH_SHORT).show();
			rdb = helper.getReadableDatabase();
			Book newbook = control.getBook(lastId, rdb);
			if(index < books.size()){
				books.set(index, newbook);
				adapter.notifyDataSetChanged();
				index++;
			}else{
				addBook(newbook);
				index++;
				for(int i = 1; i < book_row_empty; i++)
					addBook(new Book());
			}
			return false;
		}
	};

	private OnItemClickListener mOnItemClick = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position,
				long id) {
			pd.dismiss();
			gridBook.setClickable(false);
			if (books.get(position).isEmpty() == false) {
				Intent intent = new Intent(mContext,
						Foods_in_Book_Activity.class);
				intent.putExtra("ID",
						String.valueOf(books.get(position).get_id()));
				selected = position;
				startActivityForResult(intent, REQUEST_CODE_BOOK_ID);
			}
		}
	};
	
	

	@Override
	public void onResume() {
		super.onResume();
		gridBook.setClickable(true);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_BOOK_ID) {
			int book_id = Integer.parseInt(data.getStringExtra("BOOK_ID"));
			rdb = helper.getReadableDatabase();
			BookControl control = new BookControl();
			books.set(selected, control.getBook(book_id, rdb));
			adapter.notifyDataSetChanged();
		} else if(resultCode == RESULT_CANCELED){
			books.remove(selected);
			int num, addmore = 0;
			if (books.size() < book_full_empty) {
				num = books.size() / book_full_empty;
				addmore = (num + 1) * book_full_empty- books.size();
			} else {
				num = books.size() / book_row_empty;
				addmore = (num + 1) * book_row_empty - books.size();
			}
			Book book = new Book();
			for (int i = 0; i < addmore; i++) {
				addBook(book);
			}
			index--;
			adapter.notifyDataSetChanged();
		}
	}

	private void addBook(Book book) {
		books.add(book);
		adapter.notifyDataSetChanged();
	}

	private class LoadBookTask extends
			AsyncTask<Void, Integer, ArrayList<Book>> {

		@Override
		protected ArrayList<Book> doInBackground(Void... params) {
			try {
				rdb = helper.getReadableDatabase();
				BookControl control = new BookControl();
				ArrayList<Book> list = control.getAllBooks(rdb);
				return list;
			} catch (Exception e) {
				e.printStackTrace();
				finish();
			}
			return null;
		}

		@Override
		protected void onPostExecute(ArrayList<Book> result) {
			super.onPostExecute(result);
			books.clear();
			for (Book book : result) {
				addBook(book);
				index++;
			}
			int num, addmore = 0;
			if (result.size() < book_full_empty) {
				num = result.size() / book_full_empty;
				addmore = (num + 1) * book_full_empty - result.size();
			} else {
				num = result.size() / book_row_empty;
				addmore = (num + 1) * book_row_empty - result.size();
			}
			Book book = new Book();
			for (int i = 0; i < addmore; i++) {
				addBook(book);
			}

			result.clear();
			pd.dismiss();
		}

		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(mContext, R.style.MyDialogTheme);
			pd.setMessage("Loading..");
			pd.show();
		}
	}

	private void loadBook() {
		LoadBookTask task = new LoadBookTask();
		task.execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.book, menu);
		return true;
	}

}
